package com.framwork.core.config;

import com.framwork.core.base.em.RequestMappering;
import com.framwork.core.exception.EmptyValueException;
import org.apache.commons.lang3.StringUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author ：james.liu
 * @date ：Created in 2022/3/4 14:08
 * @description：
 * @version: 1.0
 */
public final class APIInterfaceMapping {

    /**
     * 描述：输入接口 参数映射
     */
    private static final Map<String, Object> inputMapping = new ConcurrentHashMap<>();

    static {
        registerAPIMapping(RequestMappering.open_apis_auth_v3_app_access_token.getMapperName(),
                "CmdId", null)
        ;

    }

    /**
     * 设置接口拼接地址
     **/
    public static final String PERFIX_SPLICING = "-splicing";
    /**
     * 设置校验参数
     **/
    private static final String PREFIX_REQUIRED = "-required";

    public static final String SET_ACCESS_TOKEN = "?access_token={0}";

    /**
     * 描述：（接口输入值）获取API 必选参数列表
     */
    public static List<String> getRequiredListInput(final String cmdId) {
        Object ob = inputMapping.get(cmdId + PREFIX_REQUIRED);
        if (Objects.isNull(ob)) {
            return null;
        }
        String o = inputMapping.get(cmdId + PREFIX_REQUIRED).toString();
        String[] split = StringUtils.split(o, ",");
        if (Objects.isNull(split)) {
            return null;
        }
        if (split.length <= 0) {
            return null;
        }
        List<String> r = Arrays.asList(split);
        return r;
    }

    /**
     * 描述：获取API 接口拼接前缀
     *
     * @param cmdId
     * @return
     */
    public static String getSplicingInput(final String cmdId) {
        Object result = inputMapping.get(cmdId + PERFIX_SPLICING);
        if (Objects.isNull(result)) {
            throw new EmptyValueException("获取接口前缀有误！");
        }
        return result.toString();
    }

    /**
     * 注册API映射表
     *
     * @param cmdId         接口名称/接口路径
     * @param inputRequired 入参需要校验部分
     */
    private static void registerAPIMapping(final String cmdId,
                                           final String inputRequired,
                                           final String inputSplicing) {
        if (StringUtils.isNotBlank(inputSplicing)) {
            inputMapping.put(cmdId + PERFIX_SPLICING, inputSplicing);
        }
        if (StringUtils.isNotBlank(inputRequired)) {
            inputMapping.put(cmdId + PREFIX_REQUIRED, inputRequired);
        }
    }
}
